package com.example.personal.aiagent.user.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.personal.aiagent.common.util.TimeUtil;
import com.example.personal.aiagent.user.constant.UserAuthority;
import com.example.personal.aiagent.user.model.entity.UserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Arrays;

public interface UserMapper extends BaseMapper<UserEntity> {
    String ID = "ID";

    String USERNAME = "USERNAME";

    String PASSWORD = "PASSWORD";

    String MODIFY_TIMESTAMP = "MODIFY_TIMESTAMP";

    String MODIFY_TIME_DISPLAY = "MODIFY_TIME_DISPLAY";

    default int insertUser(String username, String password) {
        UserEntity entity = new UserEntity();
        entity.setUsername(username);
        entity.setPassword(password);
        int currentTime = TimeUtil.getCurTimeMs();
        String currentTimeString = TimeUtil.getTimeMsString(currentTime);
        entity.setCreateTimestamp(currentTime);
        entity.setModifyTimestamp(currentTime);
        entity.setCreateTimeDisplay(currentTimeString);
        entity.setModifyTimeDisplay(currentTimeString);
        entity.setRoles(StringUtils.join(Arrays.asList(UserAuthority.INIT.getAuthority(), UserAuthority.ADMIN.getAuthority()), ","));
        return insert(entity);
    }

    default int updateUser(int id, String username, String password) {
        UpdateWrapper<UserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(USERNAME, username);
        updateWrapper.set(PASSWORD, password);
        int currentTime = TimeUtil.getCurTimeMs();
        String currentTimeString = TimeUtil.getTimeMsString(currentTime);
        updateWrapper.set(MODIFY_TIMESTAMP, currentTime);
        updateWrapper.set(MODIFY_TIME_DISPLAY, currentTimeString);
        updateWrapper.set(PASSWORD, password);
        updateWrapper.eq(ID, id);
        return update(null, updateWrapper);
    }

    default UserEntity selectByUsername(String username) {
        QueryWrapper<UserEntity> entityQueryWrapper = new QueryWrapper<>();
        entityQueryWrapper.eq(USERNAME, username);
        return selectOne(entityQueryWrapper);
    }

    @Select("<script>" +
            "select * from USER where 1 = 1 " +
            "<if test='p_id != null'> " +
            "and id=#{p_id} " +
            "</if>" +
            "<if test='p_username != null and p_username != \"\"'> " +
            "and username=#{p_username} " +
            "</if>" +
            "</script>")
    IPage<UserEntity> selectUsers(IPage<?> page, @Param("p_id") Integer id, @Param("p_username") String username);


}
